<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\RoomFission\Listener;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use MoChat\App\WorkRoom\Event\CreateRoomMemberEvent;
use MoChat\Plugin\RoomFission\Contract\RoomFissionContactContract;
use MoChat\Plugin\RoomFission\Contract\RoomFissionContract;
use Psr\Container\ContainerInterface;

/**
 * 客户群创建事件
 * 有新增客户群时，回调该事件。收到该事件后，企业可以调用获取客户群详情接口获取客户群详情。
 *
 * @Listener
 */
class CreateRoomMemberListener implements ListenerInterface
{
    /**
     * @Inject
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var StdoutLoggerInterface
     */
    private $logger;

    /**
     * @Inject
     * @var RoomFissionContract
     */
    private $roomFissionService;

    /**
     * @Inject
     * @var RoomFissionContactContract
     */
    private $roomFissionContactService;

    public function listen(): array
    {
        return [
            CreateRoomMemberEvent::class,
        ];
    }

    /**
     * @param CreateRoomMemberEvent $event
     */
    public function process(object $event)
    {
        try {
            $message = $event->message; // {"corpId":1,"rooms":[{"wx_user_id":"wmWGBlCwAAJeNzZoWXTtH1XZBNtf_ZyQ","contact_id":3,"employee_id":0,"unionid":"o92TTwHEVf8jWvYKdvb7V314iU-4","room_id":98,"join_scene":3,"type":2,"status":1,"join_time":"2022-03-15 14:16:56","out_time":"","created_at":"2022-03-15 14:17:00","updated_at":"2022-03-15 14:17:00"}]}
            $this->logger = $this->container->get(StdoutLoggerInterface::class);
            $this->roomFissionService = $this->container->get(RoomFissionContract::class);
            $this->roomFissionContactService = $this->container->get(RoomFissionContactContract::class);

            $corpId = $message['corpId'];
            $contactRoomCreateData = $message['rooms'];

            if (empty($contactRoomCreateData)) {
                return;
            }
            foreach ($contactRoomCreateData as $item) {
                if (empty($item['unionid'])) {
                    continue;
                }

                $contactRecord = $this->roomFissionContactService->getRoomFissionContactByRoomIdUnionId((int) $item['room_id'], $item['unionid'], ['id', 'fission_id', 'is_new', 'parent_union_id', 'join_status']);
                if (empty($contactRecord)) {
                    continue;
                }
                foreach ($contactRecord as $val) {
                    if ($val['joinStatus'] === 0) {
                        $fission = $this->roomFissionService->getRoomFissionById($val['fissionId'], ['target_count', 'new_friend']);
                        if (empty($fission)) {
                            continue;
                        }
                        // 入群
                        $this->roomFissionContactService->updateRoomFissionContactById($val['id'], ['join_status' => 1]);
                        // 有师傅 并且（无用户限制活新用户有效）
                        if (empty($contactRecord['parentUnionId']) && ($fission['newFriend'] === 0 || ($fission['newFriend'] === 1 && $val['isNew'] === 1))) {
                            continue;
                        }

                        $parent = $this->roomFissionContactService->getRoomFissionContactByRoomIdUnionIdFissionID((int) $item['room_id'], $val['parentUnionId'], $val['fissionId'], ['id', 'invite_count']);
                        $num = $parent['inviteCount'] + 1;
                        $status = $fission['targetCount'] > $num ? 0 : 1;
                        $this->roomFissionContactService->updateRoomFissionContactById($parent['id'], ['invite_count' => $num, 'status' => $status]);
                    }
                }
            }
        } catch (\Throwable $e) {
            $this->logger->error(sprintf('[群裂变客户成员创建事件]监听失败，错误信息: %s', $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
        }
    }
}
